package com.example.fullexample.config;

import com.example.fullexample.util.ApplicationContextHolder;
import com.example.fullexample.util.Subscriber;
import com.google.common.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Configuration
public class BusConfig implements ApplicationListener<ApplicationStartedEvent> {
    @Autowired
    private ApplicationContext context;

    @Bean
    public EventBus bus() {
        return new EventBus("bus");
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {

        String[] serviceNames = context.getBeanNamesForAnnotation(Subscriber.class);
        for (String serviceName : serviceNames) {
            System.out.println("注册：" + serviceName);
            bus().register(context.getBean(serviceName));
        }
    }
}
